//fly.config.headers['Content-Type'] = 'multipart/form-data'
import appConfig from '@/appConfig'
var api = {
  /**
   * 选择图片
   */
  chooseImg(that, name) {
    wx.chooseImage({
      count: 1, // 最多可以选择的图片张数，默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        var tempFiles = res.tempFiles
        var file = tempFiles[0]
        //启动上传等待中...
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 1000
        })
        api.uploadImg(that, file, name)
      },
      fail: function() {
        // fail
      },
      complete: function() {
        // complete
      }
    })
  },
  /**
   *上传图片
   */
  uploadImg(that, file, name) {
    wx.uploadFile({
      url: appConfig.uploadUrl, //后台上传接口地址
      filePath: file.path,
      name: 'file',
      formData: {
        type: 'wxWorker-' + name,
        file: file
      },
      header: {
        'Content-Type': 'multipart/form-data'
      },
      success: function(res) {
        var data = JSON.parse(res.data)
        that.workerForm[name] = data.data.filePath
        that[name + 'Url'] =
          appConfig.imgUrl + that.workerForm[name]
      },
      fail: function(res) {
        wx.hideToast()
        wx.showModal({
          title: '错误提示',
          content: '上传图片失败',
          showCancel: false,
          success: function(res) {}
        })
      }
    })
  },
  deleteImg(that, name) {
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function(res) {
        if (res.confirm) {
          console.log(name)
          console.log(that.workerForm)
          that.workerForm[name] = undefined
          that[name + 'Url'] = appConfig.imgUrl
        } else if (res.cancel) {
          console.log('点击取消了')
          return false
        }
      }
    })
  }
}

export { api }
